package com.course.generator.util;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

/**
 * 模板生成工具类
 * @author: Durian
 * @date: 2021/5/1 13:18
 */
public class FreeMakerUtils {

    private static final String templatePath = "/template";

    private static Template temp;

    private static void initConfig(String templateName) throws IOException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
        cfg.setClassForTemplateLoading(FreeMakerUtils.class, templatePath);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_29));
        temp = cfg.getTemplate(templateName);
    }

    private static void generator(String fileName, Map<String, Object> map) throws IOException, TemplateException {
        FileWriter fw = new FileWriter(fileName);
        BufferedWriter bw = new BufferedWriter(fw);
        temp.process(map, bw);
        bw.flush();
        fw.close();
    }

    public static void generator(String templateName, String fileName, Map<String, Object> map) throws IOException, TemplateException {
        initConfig(templateName);
        generator(fileName, map);
    }
}